package com.pwser.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.pwser.po.ShiroMenu;
import com.pwser.po.ShiroRole;
import com.pwser.po.ShiroUser;

@SuppressWarnings("all")
@Component
public class UserService {
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	public ShiroUser findUserByLoginAccount(String loginAccount) {
		String sql = "SELECT * FROM SHIRO_USER WHERE LOGIN_ACCOUNT = ?";
		RowMapper<ShiroUser> rowMapper = new BeanPropertyRowMapper<ShiroUser>(ShiroUser.class);
		ShiroUser user = jdbcTemplate.queryForObject(sql, rowMapper, new String[]{loginAccount});
		return user;
	}
	
	public List<String> findRolesByLoginAccount(String loginAccount) {
		List<String> roles = new ArrayList<String>();
		String sql = "SELECT ROLE_NAME FROM SHIRO_USER_ROLE UR LEFT JOIN SHIRO_ROLE R ON UR.ROLE_ID=R.ROLE_ID LEFT JOIN SHIRO_USER U ON UR.USER_ID=U.USER_ID WHERE U.LOGIN_ACCOUNT = ?";
		RowMapper<ShiroRole> rowMapper = new BeanPropertyRowMapper<ShiroRole>(ShiroRole.class);
		List<ShiroRole> rolelist = jdbcTemplate.query(sql, rowMapper, new String[]{loginAccount});
		for(ShiroRole role : rolelist){
			roles.add(role.getRoleName());
		}
		return roles;
	}
	
	public List<String> findMenusByLoginAccount(List<String> roles) {
		String roleStr = "";
		for(String role : roles){
			roleStr += "'"+role+"',"; 
		}
		if(roleStr.length() > 0){
			roleStr = roleStr.substring(0, roleStr.length()-1);
		}else{
			roleStr = "'-1'";
		}
		List<String> menus = new ArrayList<String>();
		String sql = "SELECT MENU_NAME FROM SHIRO_ROLE_MENU RM LEFT JOIN SHIRO_ROLE R ON RM.ROLE_ID=R.ROLE_ID LEFT JOIN SHIRO_MENU M ON RM.MENU_ID=M.MENU_ID WHERE R.ROLE_NAME in ("+roleStr+")";
		RowMapper<ShiroMenu> rowMapper = new BeanPropertyRowMapper<ShiroMenu>(ShiroMenu.class);
		List<ShiroMenu> menulist = jdbcTemplate.query(sql, rowMapper);
		for(ShiroMenu menu : menulist){
			menus.add(menu.getMenuName());
		}
		return menus;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
}
